﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Repository;

using WarehouseManagement.Presenters.Import;
using WarehouseManagement.ViewModels.Import;
using WarehouseManagement.Views.Shared;
using DevExpress.XtraGrid.Views.Grid;
using WarehouseManagement.DataAccess;

using WarehouseManagement.Shared;
using WarehouseManagement.BusinessLogic.BC;
using DevExpress.XtraBars;
using WarehouseManagement.BusinessLogic.DTO;
using WarehouseManagement.ViewModels.PO;
using WarehouseManagement.Presenters.PO;
using WarehouseManagement.Views.Export;
using DevExpress.XtraReports.UI;
using DevExpress.LookAndFeel;
using WarehouseManagement.Views.Supplier;
using WarehouseManagement.Views.Merchandise;

namespace WarehouseManagement.Views.PO
{
    public partial class NewEditPO : XtraForm, IView<NewEditPOPresenter>, INewEditPOViewModel
    {
        private NewEditPOPresenter _presenter;
        //public enum EditMode { New, EditExisting }
        private NewEditImport.EditMode _editMode;
        public NewEditPOPresenter.POSaved OnImportSaved;
        private CurrencyBC _currencyBC;

        private PODTO _po;

        private bool _dataChanged = false;
        private bool _dataSaved = false;

        private NewEditPO()
        {

            InitializeComponent();
            _currencyBC = new CurrencyBC();
            _presenter = SetupPresenter();
        }



        public NewEditPO(WarehouseManagement.Views.Export.NewEditImport.EditMode mode)
            : this()
        {
            _po = new PODTO();
            CurrentEditMode = mode;
            txtImportDate.Properties.MaxValue = DateTime.Now;
            if (CurrentEditMode == WarehouseManagement.Views.Export.NewEditImport.EditMode.New)
                _presenter.CreateNewImportNumber();
            _presenter.InitializeView();


        }

        public int MerchandiseId { get; set; }
        public decimal UnitPriceAfterTax { get; set; }
        //public void LoadImportListOnDemand()
        //{
        //    _presenter.LoadImportList(ImportNumber, this.MerchandiseId);
        //}

        public NewEditPOPresenter SetupPresenter()
        {
            var p = new NewEditPOPresenter();
            p.RegisterViewModel(this);
            return p;
        }



        private void NewImport_Load(object sender, EventArgs e)
        {

            btnCreateNewImportNumber.Enabled = (_editMode != WarehouseManagement.Views.Export.NewEditImport.EditMode.New);
            HandleControls();
            if (_editMode == WarehouseManagement.Views.Export.NewEditImport.EditMode.EditExisting)
            {
                _presenter.LoadExistingPOList(PONumber);
            }
            lkCurrency_EditValueChanged(lkCurrency, e);



            _po.PONumber = this.PONumber;
            _po.PODate = this.PODate;


        }

        private void grvImportList_CustomDrawRowIndicator(object sender, DevExpress.XtraGrid.Views.Grid.RowIndicatorCustomDrawEventArgs e)
        {
            if (e.RowHandle == -2147483648 || e.RowHandle == -2147483647)
                return;
            e.Info.DisplayText = (e.RowHandle + 1).ToString();
        }

        //public void LoadImportListFromPO()
        //{
        //    POBC poBC = new POBC();
        //    var poId = poBC.GetPOIdByNumber(this.ImportForDocumentNumber);
        //    if (poId == Guid.Empty)
        //        return;
        //    var list = poBC.GetPOList(poId);
        //    var list2 = list.Select(e => new PODetailDTO()
        //    {
        //        CreatedBy = GlobalMemory.CurrentLoginUser,
        //        CreatedDate = DateTime.Now,
        //        ExchangeRate = e.PO.ExchangeRate,
        //        Id = Guid.NewGuid(),
        //        ImportId = this.ImportId,
        //        MerchandiseId = e.MerchandiseId,
        //        OriginPrice = e.UnitPrice,
        //        Quantity = e.Quantity,
        //        ShippingFee = e.ShippingFee,
        //        Tax = e.Tax
        //    });

        //    foreach(var item in list2)
        //    {
        //        PODetailList.Add(item);
        //    }
        //}


        public Guid POId
        {
            get
            {
                return Guid.Parse(this.Tag.ToString());
            }
            set
            {
                this.Tag = value;
            }
        }

        public DateTime PODate
        {
            get
            {
                return txtImportDate.DateTime;
            }
            set
            {
                txtImportDate.DateTime = value;
            }
        }


        public string Notes
        {
            get
            {
                return txtNotes.Text;
            }
            set
            {
                txtNotes.Text = value;
            }
        }

        public BindingList<PODetailDTO> PODetailList
        {
            get
            {
                return grdPOList.DataSource as BindingList<PODetailDTO>;
            }
            set
            {
                grdPOList.DataSource = value;
            }
        }


        public IEnumerable<dynamic> MerchandiseList
        {
            get
            {
                return ipeMerchandiseLookup.DataSource as IEnumerable<dynamic>;
            }
            set
            {
                ipeMerchandiseLookup.DataSource = value;
                ipeMerchandiseLookup.NullText = "(Chọn mặt hàng)";
                ipeMerchandiseLookup.ValueMember = "MerchandiseId";
                ipeMerchandiseLookup.DisplayMember = "MerchandiseName";




            }
        }

        private void grvImportList_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            _dataChanged = true;
            var row = grvPOList.GetFocusedRow() as PODetailDTO;

            row.ExchangeRate = this.ExchangeRate;
            row.PO = _po;
        }

        //private List<WarehouseManagement.DataAccess.ImportDetail> _importDetails = new List<WarehouseManagement.DataAccess.ImportDetail>();

        private void grvImportList_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            var fr = grvPOList.GetFocusedRow() as ImportDetailDTO;

            _dataChanged = true;
            _dataSaved = false;
            btnCreateNewImportNumber.Enabled = true;
        }

        private void grvImportList_CellValueChanging(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {

        }

        private void ipeMerchandiseLookup_EditValueChanged(object sender, EventArgs e)
        {
            var edit = sender as GridLookUpEdit;
            //var view = edit.Properties.View as DevExpress.XtraGrid.Views.Grid.GridView;

            var fr = grvPOList.GetFocusedRow() as PODetailDTO;

            var selectedItem = (dynamic)edit.GetSelectedDataRow();
            fr.MerchandiseUnit = selectedItem.MerchandiseUnit;
            fr.MerchandiseName = selectedItem.MerchandiseName;
            fr.MerchandiseCategory = selectedItem.MerchandiseCategory;
        }



        public IEnumerable<CurrencyDTO> CurrencyList
        {
            get
            {
                return lkCurrency.Properties.DataSource as IEnumerable<CurrencyDTO>;
            }
            set
            {
                lkCurrency.Properties.DisplayMember = "CurrencyCode";
                lkCurrency.Properties.ValueMember = "CurrencyCode";
                lkCurrency.Properties.DataSource = value;
                lkCurrency.EditValue = "VND";
            }
        }

        private void lkCurrency_EditValueChanged(object sender, EventArgs e)
        {
            var edit = sender as LookUpEdit;
            if (_editMode == WarehouseManagement.Views.Export.NewEditImport.EditMode.New)
            {
                var abc = edit.GetColumnValue("ExchangeRateVND");
                if (abc != null)
                {
                    var exchangeRate = decimal.Parse(abc.ToString());

                    AssignExchangeRate(exchangeRate);
                }
            }
            var ex = edit.GetColumnValue("ExchangeRateVND");
            if (ex != null)
            {
                _po.ExchangeRate = decimal.Parse(ex.ToString());
                _po.CurrencyName = edit.GetColumnValue("CurrencyName").ToString();
            }
        }

        private void AssignExchangeRate(decimal value)
        {
            ExchangeRate = value;
            foreach (var item in PODetailList)
            {
                item.ExchangeRate = ExchangeRate;
            }
            grvPOList.RefreshData();
        }

        private void grvImportList_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {

            //var quantity = Convert.ToDecimal(grvImportList.GetRowCellValue(e.RowHandle, colQuantity));
            //if (quantity < 1)
            //{
            //    e.Valid = false;
            //    e.ErrorText = "Bạn hãy xem lại số lượng";
            //}
            var errorList = ValidateImportItem(e.RowHandle);
            if (errorList.Count() > 0)
            {
                e.Valid = false;
                e.ErrorText = string.Join("\n", errorList);
            }
        }

        private IEnumerable<string> ValidateImportItem(int rowHandle)
        {
            var colMerchandise = grvPOList.GetRowCellValue(rowHandle, this.colMerchandise);

            if (colMerchandise == null || Convert.ToInt32(colMerchandise) == 0)
            {
                yield return "Bạn chưa chọn mặt hàng";
            }

            var quantity = Convert.ToDecimal(grvPOList.GetRowCellValue(rowHandle, this.colQuantity));
            if (quantity < 1)
            {
                yield return "Bạn hãy xem lại số lượng nhập";
            }
        }

        private void grvImportList_ValidatingEditor(object sender, DevExpress.XtraEditors.Controls.BaseContainerValidateEditorEventArgs e)
        {
            if (grvPOList.FocusedColumn.FieldName == "Quantity")
            {
                if (Convert.ToDecimal(e.Value) < 1)
                {
                    e.ErrorText = "Bạn hãy xem lại số lượng nhập";
                    e.Valid = false;
                }
            }

        }




        public Guid SelectedPOItem
        {
            get
            {
                var handle = grvPOList.FocusedRowHandle;
                var row = grvPOList.GetRow(handle) as dynamic;
                if (row == null)
                    return Guid.Empty;
                return row.Id;
            }
            set
            {
                throw new NotImplementedException();
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (XtraMessageBox.Show("Bạn có chắc muốn xóa dòng này?", "Xóa", MessageBoxButtons.YesNo, MessageBoxIcon.Asterisk) == System.Windows.Forms.DialogResult.No)
                return;
            _presenter.DeleteSelectedItem();
            _dataChanged = true;
            _dataSaved = false;
        }

        private void ipeMerchandiseLookup_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                NewEditMerchandise frm = new NewEditMerchandise();
                frm.OnMerchandiseSaved = new NewEditMerchandise.MerchandiseSavedHandler(OnMerchandiseAdded);
                frm.ShowDialog();
            }
        }

        private void OnMerchandiseAdded(bool success, bool isEdit)
        {
            _presenter.LoadMerchandiseLookupData();
        }

        private void grvImportList_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            HandleControls();
        }

        private void HandleControls()
        {

            btnDelete.Enabled = (this.SelectedPOItem != Guid.Empty);
            btnPrint.Enabled = (this.PODetailList.Count > 0);
            if (_editMode == WarehouseManagement.Views.Export.NewEditImport.EditMode.New)
            {
                btnSave.Enabled = this.PODetailList.Count > 0;

            }
            else
            {

            }
        }

        private void labelControl2_Click(object sender, EventArgs e)
        {

        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (!ValidatePO())
            {
                XtraMessageBox.Show("Bạn chưa chọn nhà cung cấp", "Chọn nhà cung cấp", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            _presenter.OnPOSaved = new NewEditPOPresenter.POSaved(onImportSaved);
            _presenter.SavePO();

        }

        private bool ValidatePO()
        {
            if (SupplierId == -1)
            {
                return false;
            }
            return true;
        }
        private void onImportSaved(bool success)
        {
            if (success)
            {
                _dataSaved = true;
                CurrentEditMode = WarehouseManagement.Views.Export.NewEditImport.EditMode.EditExisting;
                //txtImportDate.Enabled = false;
                XtraMessageBox.Show("Tất cả thông tin đã được lưu.", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Information);
            }
            else
            {
                XtraMessageBox.Show("Đã xảy ra lỗi. Thông tin mới tạo hiện vẫn chưa được lưu và không ảnh hưởng tới dữ liệu cũ, bạn hãy thử lại sau", "Lỗi khi tạo đơn đặt hàng", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
            if (this.OnImportSaved != null)
                OnImportSaved(success);
        }

        public void RefreshDataControls()
        {
            _presenter.LoadCurrencyLookupData();
            _presenter.LoadMerchandiseLookupData();
        }
        private void btnCreateNewImportNumber_Click(object sender, EventArgs e)
        {
            if (_dataChanged && !_dataSaved)
            {
                if (XtraMessageBox.Show("Dữ liệu chưa được lưu, bạn có chắc muốn tạo đơn đặt hàng mới?", "Tạo đơn đặt hàng mới", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == System.Windows.Forms.DialogResult.No)
                    return;
            }
            _presenter.CreateNewImportNumber();
            _editMode = WarehouseManagement.Views.Export.NewEditImport.EditMode.New;

            //txtImportDate.Enabled = true;
            btnCreateNewImportNumber.Enabled = false;
        }


        public string PONumber
        {
            get
            {
                return txtImportNumber.Text;
            }
            set
            {
                txtImportNumber.Text = value;
            }
        }


        public WarehouseManagement.Views.Export.NewEditImport.EditMode CurrentEditMode
        {
            get
            {
                return _editMode;
            }
            set
            {
                _editMode = value;
                if (_editMode == WarehouseManagement.Views.Export.NewEditImport.EditMode.New)
                {

                    //txtImportDate.Enabled = true;
                    lkSupplier.Enabled = true;
                    lkCurrency.Enabled = true;
                }
                else
                {
                    //txtImportDate.Enabled = false;
                    lkSupplier.Enabled = false;
                    lkCurrency.Enabled = false;
                }
            }
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void NewEditImport_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (_dataChanged && !_dataSaved)
            {
                var result = XtraMessageBox.Show("Dữ liệu chưa được lưu, bạn có muốn lưu trước khi đóng không?", "Lưu dữ liệu",
                   MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
                if (result == DialogResult.Cancel)
                    e.Cancel = true;
                if (result == System.Windows.Forms.DialogResult.Yes)
                {
                    if (!ValidatePO())
                        e.Cancel = true;
                    btnSave_Click(sender, (EventArgs)e);

                }
            }
        }




        public int UsedCurrencyId
        {
            get
            {
                var item = lkCurrency.GetSelectedDataRow() as CurrencyDTO;
                return item.CurrencyId;
            }
            set
            {
                if (CurrencyList == null || CurrencyList.Count() == 0)
                {
                    _presenter.LoadCurrencyLookupData();
                }
                lkCurrency.EditValue = _currencyBC.GetCurrencyById(value).CurrencyCode;
            }
        }

        public decimal ExchangeRate
        {
            get
            {
                return txtExchangeRate.Value;
            }
            set
            {
                txtExchangeRate.Value = value;
            }
        }

        public void EnableCurrencySelection(bool enabled)
        {
            lkCurrency.Enabled = enabled;
        }
        public void EnableSupplierSelection(bool enabled)
        {
            lkSupplier.Enabled = enabled;
        }


        public int SupplierId
        {
            get
            {
                try
                {
                    return Convert.ToInt32(lkSupplier.EditValue);
                }
                catch { return -1; }
            }
            set
            {
                lkSupplier.EditValue = value;
            }
        }


        public IEnumerable<SupplierDTO> SupplierList
        {
            get
            {
                return lkSupplier.Properties.DataSource as IEnumerable<SupplierDTO>;
            }
            set
            {
                lkSupplier.Properties.DisplayMember = "SupplierName";
                lkSupplier.Properties.ValueMember = "Id";
                lkSupplier.Properties.DataSource = value;
                lkSupplier.Properties.PopupFormSize = new Size(lkSupplier.Size.Width, 200);

            }
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            var rptPO = new XtraReport1();
            rptPO.Parameters["Notes"].Visible = false;
            rptPO.Parameters["Notes"].Value = Notes;

            using (ReportPrintTool printTool = new ReportPrintTool(rptPO))
            {
                // Invoke the Print Preview form modally, 
                // and load the report document into it.
                rptPO.DataSource = this.PODetailList.ToList();
                printTool.ShowPreviewDialog();

                // Invoke the Print Preview form
                // with the specified look and feel setting.
                printTool.ShowPreview(UserLookAndFeel.Default);
            }
        }

        private void lkSupplier_EditValueChanged(object sender, EventArgs e)
        {
            _po.SupplierName = (this.lkSupplier.GetSelectedDataRow() as SupplierDTO).SupplierName;
        }

        private void lkSupplier_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Plus)
            {
                NewEditSupplier frm = new NewEditSupplier(false);
                frm.OnOperationCompleted = new NewEditSupplier.OperationCompleted(NewEditSupplier_Completed);
                frm.ShowDialog();
            }
        }

        private void NewEditSupplier_Completed(bool success, bool isEditMode)
        {
            _presenter.LoadSupplierList();
        }

        private void lkCurrency_ButtonClick(object sender, DevExpress.XtraEditors.Controls.ButtonPressedEventArgs e)
        {
            if (e.Button.Kind == DevExpress.XtraEditors.Controls.ButtonPredefines.Ellipsis)
            {
                _presenter.LoadCurrencyLookupData();
            }
        }


    }
}
